//
//  AppDelegate.m
//  Hxcsfw
//
//  Created by 企友软mac on 2017/10/24.
//  Copyright © 2017年 企友软mac. All rights reserved.
//

#import "AppDelegate.h"
#import "MainViewController.h"
#import "NewfeatureViewController.h"
#import <UMSocialCore/UMSocialCore.h>
#import "CheckNetwork.h"
#import "PushShowViewController.h"
#import "AFNetworkReachabilityManager.h"

// 引入JPush功能所需头文件
#import "JPUSHService.h"

// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

#define USHARE_DEMO_APPKEY @"5a600d6ca40fa3196d000086"

@interface AppDelegate ()<JPUSHRegisterDelegate,UIAlertViewDelegate>

@property(nonatomic,strong)AFNetworkReachabilityManager *reachabilityManager;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    //创建网络监控对象
    self.reachabilityManager = [AFNetworkReachabilityManager sharedManager];

    __weak __typeof(self) weakSelf = self;
    //设置监听
    [_reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

        if (((status == AFNetworkReachabilityStatusReachableViaWWAN) || (status == AFNetworkReachabilityStatusReachableViaWiFi)) && PCReleaseFlag) {
            [WShareUtil YJJCDataRequest:PCReleaseURL success:^(NSString *successUrl) {
                WLog(@"%@",successUrl);
                [weakSelf loadMainControlApplication:application didFinishLaunchingWithOptions:launchOptions];
            } failure:^(NSString *failureUrl) {
                WLog(@"%@",failureUrl);
                [weakSelf loadMainControlApplication:application didFinishLaunchingWithOptions:launchOptions];
            }];

        } else {
            [weakSelf loadMainControlApplication:application didFinishLaunchingWithOptions:launchOptions];
        }
    }];

    //开始监听网络状况.
    [_reachabilityManager startMonitoring];

    return YES;
}

// 抽出来的方法
- (void)loadMainControlApplication:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    [WShareUtil sharedData].isShowWait = YES;
    [WShareUtil sharedData].isFristStart = YES;
    //    NSString *username = [WShareUtil getDataWithUserDefaultsForKey:@"USERNAME"];
    //    NSString *password = [WShareUtil getDataWithUserDefaultsForKey:@"PASSWORD"];
    //    if (username && password) {
    //        [self requestLogin:username password:password];
    //    }

    [[CheckNetwork checkNetwork] isNetworkReachable];

    [WShareUtil sharedData].dicSession = [WShareUtil getDataWithUserDefaultsForKey:@"DICSESSION"];

    if ([WShareUtil sharedData].dicSession) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"LoginSuccess" object:nil];
    }

    /* 打开调试日志 */
    [[UMSocialManager defaultManager] openLog:YES];

    /* 设置友盟appkey */
    [[UMSocialManager defaultManager] setUmSocialAppkey:USHARE_DEMO_APPKEY];

    [self configUSharePlatforms];

    [self confitUShareSettings];

    //    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];

    NSString *versionKey = @"CFBundleVersion";
    // 上一次的使用版本（存储在沙盒中的版本号）
    NSString *lastVersion = [[NSUserDefaults standardUserDefaults] objectForKey:versionKey];
    [WShareUtil sharedData].LASTVersion = lastVersion;
    // 当前app的版本号（从Info.plist中获得）
    NSString *currentVersion = [NSBundle mainBundle].infoDictionary[versionKey];
    WLog(@"沙盒中的版本号%@",lastVersion);
    WLog(@"Info.plist中获得版本号%@",currentVersion);
    if ([lastVersion isEqualToString:currentVersion]) {
        self.window.rootViewController = [[MainViewController alloc] init];
    } else {
        self.window.rootViewController = [[NewfeatureViewController alloc] init];
        [[NSUserDefaults standardUserDefaults] setObject:currentVersion forKey:versionKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }

    [self getData];

    [self.window makeKeyAndVisible];

    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];

    //    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString] ;


    NSString *strAppKey = @"290e82339a6a05d565b92236";

    // 公司的极光推送
//    NSString *strAppKey = @"dad82f20a8d9e81d262cc4b4";

    [JPUSHService setupWithOption:launchOptions appKey:strAppKey
                          channel:@""
                 apsForProduction:YES
            advertisingIdentifier:@""];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];

    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            WLog(@"registrationID获取成功：%@",registrationID);
        }
        else{
            WLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];

    //JPush 监听登录成功
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(networkDidLogin:)
                                                 name:kJPFNetworkDidLoginNotification
                                               object:nil];
}


- (void)applicationWillResignActive:(UIApplication *)application {

    id versionDic = [WShareUtil getDataWithUserDefaultsForKey:@"_versionCode"];

    NSString *isRequired = [NSString stringWithFormat:@"%@",versionDic[@"required"]];

    if ([isRequired boolValue]) {
        [self update:versionDic[@"versionCode"] isRequired:isRequired];
    }
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    if (@available(iOS 11.0, *)) {
        [UIApplication sharedApplication].applicationIconBadgeNumber = -1;
    } else {
        UILocalNotification *localNotification = [[UILocalNotification alloc] init];
        localNotification.fireDate = [NSDate date];
        localNotification.applicationIconBadgeNumber = -1;
        [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
    }
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    [JPUSHService resetBadge];
    [application cancelAllLocalNotifications];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark - URL
// 支持所有iOS系统
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

- (void)confitUShareSettings
{
    /*
     * 打开图片水印
     */
    //[UMSocialGlobal shareInstance].isUsingWaterMark = YES;
    
    /*
     * 关闭强制验证https，可允许http图片分享，但需要在info.plist设置安全域名
     <key>NSAppTransportSecurity</key>
     <dict>
     <key>NSAllowsArbitraryLoads</key>
     <true/>
     </dict>
     */
    //[UMSocialGlobal shareInstance].isUsingHttpsWhenShareContent = NO;
}

- (void)configUSharePlatforms
{
    /* 设置微信的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wxfba2a35c0aae0bde" appSecret:@"SXHTJSsxhtjs2017sxhtjs2017sxhtjs" redirectURL:@"http://mobile.umeng.com/social"];
    
    /* 设置分享到QQ互联的appID
     * U-Share SDK为了兼容大部分平台命名，统一用appKey和appSecret进行参数设置，而QQ平台仅需将appID作为U-Share的appKey参数传进即可。
     */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"1106526131"/*设置QQ平台的appID*/  appSecret:nil redirectURL:@"http://mobile.umeng.com/social"];
    
    /* 支付宝的appKey */
    /*[[UMSocialManager defaultManager] setPlaform: UMSocialPlatformType_AlipaySession appKey:@"2015111700822536" appSecret:nil redirectURL:@"http://mobile.umeng.com/social"];*/

}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    WLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#pragma mark- JPUSHRegisterDelegate

- (void)networkDidLogin:(NSNotification *)notification {

    if ([WShareUtil sharedData].dicSession) {

        NSString *alias = @"cst123456";
        NSSet *setTag = [[NSSet alloc] initWithObjects:@"register_soldier",nil];

        alias = [WShareUtil sharedData].dicSession[@"userid"];
        alias = [NSString stringWithFormat:@"cst%@",alias];
        NSDictionary *dic = [WShareUtil sharedData].dicSession;
        NSString *k = [NSString stringWithFormat:@"%@",dic[@"gid"]];
        if ([k isEqualToString:@"0"]) {
            setTag = [[NSSet alloc] initWithObjects:@"register_soldier",nil];
        }else if([k isEqualToString:@"2"]){
            setTag = [[NSSet alloc] initWithObjects:@"common_soldier",nil];
        }else if ([k isEqualToString:@"3"]){
            setTag = [[NSSet alloc] initWithObjects:@"silver_soldier",nil];
        }else if ([k isEqualToString:@"4"]){
            setTag = [[NSSet alloc] initWithObjects:@"gold_soldier",nil];
        }

        [JPUSHService setTags:setTag completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
            WLog(@"%@setTag",setTag);
        } seq:11];
        //    设置别名 seq 10;
        [JPUSHService setAlias:alias completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
            WLog(@"%@iAlias",iAlias);
        } seq:10];
        [[NSNotificationCenter defaultCenter] removeObserver:self
                                                        name:kJPFNetworkDidLoginNotification
                                                      object:nil];
    }

}

//============================

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
- (void)application:(UIApplication *)application
didRegisterUserNotificationSettings:
(UIUserNotificationSettings *)notificationSettings {

    WLog(@"ios7c");

}

// Called when your app has been activated by the user selecting an action from
// a local notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forLocalNotification:(UILocalNotification *)notification
  completionHandler:(void (^)())completionHandler {

}

// Called when your app has been activated by the user selecting an action from
// a remote notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forRemoteNotification:(NSDictionary *)userInfo
  completionHandler:(void (^)())completionHandler {

}
#endif

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [JPUSHService handleRemoteNotification:userInfo];
    WLog(@"iOS6及以下系统，收到通知:%@", [self logDic:userInfo]);
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
    [JPUSHService handleRemoteNotification:userInfo];
    WLog(@"iOS7及以上系统，收到通知:%@", [self logDic:userInfo]);

    if ([[UIDevice currentDevice].systemVersion floatValue]<10.0 || application.applicationState>0) {
    }

    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
}

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    NSDictionary * userInfo = notification.request.content.userInfo;
    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    //
    //    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题

    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        WLog(@"iOS10 前台收到远程通知:%@", [self logDic:userInfo]);
    }
    else {
        // 判断为本地通知
        //        WLog(@"iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {

    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容

    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题

    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        WLog(@"iOS10 收到远程通知:%@", [self logDic:userInfo]);
    }
    else {
        // 判断为本地通知
        WLog(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);

        if ([WShareUtil sharedData].dicSession) {
//            HHBaseTabBar *tab = [WShareUtil sharedData].tabBar;
//            [WShareUtil sharedData].tabBar.selectedIndex = 3;
            //            dd
            //            MyAdvisoryViewController *myAdvisoryVC = [[MyAdvisoryViewController alloc]init];
            //            //跳转时隐藏标签栏
            //            myAdvisoryVC.hidesBottomBarWhenPushed=YES;
            //            [self.window.rootViewController.navigationController pushViewController:myAdvisoryVC animated:YES];
        }
    }

    MainViewController *mainVc = (MainViewController *)self.window.rootViewController;
    PushShowViewController *pushShowVc = [[PushShowViewController alloc] init];
    pushShowVc.title = @"推送消息";
    pushShowVc.strContent = body;

    NSUInteger index = [WShareUtil sharedData].tabbarIndex;
    [mainVc.viewControllers[index] pushViewController:pushShowVc animated:NO];

    completionHandler();  // 系统要求执行这个方法
}
#endif

// log NSSet with UTF8
// if not ,log will be \Uxxx
- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str =
    [NSPropertyListSerialization propertyListFromData:tempData
                                     mutabilityOption:NSPropertyListImmutable
                                               format:NULL
                                     errorDescription:NULL];
    return str;
}

#pragma mark 获取自定义消息内容

- (void)networkDidReceiveMessage:(NSNotification *)notification {

    NSDictionary * userInfo = [notification userInfo];
    //    NSString *content = [userInfo valueForKey:@"content"];
    //    NSString *content_type = [userInfo valueForKey:@"content_type"];
    //    NSString *strTitle = [userInfo valueForKey:@"title"];
    //
    //    NSDictionary *extras = [userInfo valueForKey:@"extras"];
    //    NSString *replyid = [extras valueForKey:@"replyid"];
    //
    //    NSString *customizeField1 = [extras valueForKey:@"cst123456"]; //自定义参数，key是自己定义的

    NSInteger badge = [UIApplication sharedApplication].applicationIconBadgeNumber;
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:badge+1];
    [JPUSHService setBadge:badge+1];
    [self addLocalNotification:userInfo];
}

- (void)addLocalNotification:(NSDictionary *)userInfo{

    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
        NSUInteger status = [settings authorizationStatus];
        WLog(@"当前的权限是？ %lu", status);
        // 初始化本地通知对象
        UILocalNotification *notification = [[UILocalNotification alloc] init];
        notification.alertTitle = @"您提出的问题有了新的回复，请在咨询列表去查询";
        // 设置提醒的文字内容
        notification.alertBody = [userInfo valueForKey:@"content"];
        // 通知提示音 使用默认的
        notification.soundName= UILocalNotificationDefaultSoundName;
        // 将通知添加到系统中
        [[UIApplication sharedApplication] presentLocalNotificationNow:notification];

        // 新系统
        //        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
        //        content.title = @"您提出的问题有了新的回复，请在咨询列表去查询";
        //        content.subtitle = [userInfo valueForKey:@"content"];
        ////        content.body = [NSString localizedUserNotificationStringForKey:@"jkljk" arguments:nil];
        //
        //        content.sound = [UNNotificationSound defaultSound];
        ////        content.badge = @1;
        ////        content.launchImageName = @"banner";
        ////
        ////        NSString *path1 = [[NSBundle mainBundle] pathForResource:@"banner" ofType:@"png"];
        ////        NSString *path2 = [[NSBundle mainBundle] pathForResource:@"banner" ofType:@"png"];
        ////        NSError *error;
        ////
        ////        UNNotificationAttachment *att = [UNNotificationAttachment attachmentWithIdentifier:@"dd" URL:[NSURL fileURLWithPath:path2] options:nil error:&error];
        ////        UNNotificationAttachment *att3 = [UNNotificationAttachment attachmentWithIdentifier:@"dd" URL:[NSURL fileURLWithPath:path2] options:nil error:&error];
        ////        content.attachments = @[att, att3];
        //
        //        UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:3 repeats:NO];
        //
        //        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"TimeSecond" content:content trigger:trigger];
        //
        //        [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        //            WLog(@"成功添加推送");
        //        }];
    }];
}

// 自动登录功能
- (void)requestLogin:(NSString *)username password:(NSString *)password{

    NSDictionary *parametersDict = @{@"mode":@"native",@"service":@"login",@"content":@{@"username":username,@"password":password}};

    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:secret]};


    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];
        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];

        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        if ([successStr boolValue]) {
//            [SVProgressHUD showImage:nil status:@"登录成功"];
//            [SVProgressHUD setOffsetFromCenter:UIOffsetMake(0, WSCREENH_HEIGHT *0.5 - 70)];
//            [SVProgressHUD dismissWithDelay:1.];
//            [SVProgressHUD setBackgroundColor:[UIColor colorWithRed:0.9 green:0.91 blue:0.93 alpha:1]];   //背景颜色

            [WShareUtil sharedData].dicSession = returnDic;
            [[NSNotificationCenter defaultCenter] postNotificationName:@"LoginSuccess" object:nil];

        }

    } failure:^(NSError *error) {
        WLog(@"登录失败");
    } showProgress:YES];
}

#pragma mark - 接口获取版本号
-(void)getData {

    NSDictionary *parametersDict = @{@"mode":@"native",@"service":@"preload",@"content":@{@"revert":@"version",@"device":@"1"}};
    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:secret]};


    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];
        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];
        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        //        if([returnDic[@"resultCode"] isEqualToString:@"NO_VALIBLE_VERSION"]){
        //            WLog(@"errorInfo:当前版本为最新版本");
        //            UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"有新版本了，快去下载吧" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        //            [av show];
        //            isUpdate = YES;
        //        }

        if ([successStr boolValue]) {
            _content = [returnDic objectForKey:@"content"];//版本内容

            _content = [WShareUtil filterHTML:_content];
            _content = [_content stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];//去掉特殊符号
            _content = [_content stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];//去掉左右两端的空格

            _appPath = [returnDic objectForKey:@"appPath"];//下载地址
            //[WShareUtil sharedData].appDownloadUrl = [returnDic objectForKey:@"appPath"];//下载地址添加到单例中
            _versionCode = [returnDic objectForKey:@"versionCode"];//版本号

            NSString *isRequired = [NSString stringWithFormat:@"%@",returnDic[@"required"]];

            [WShareUtil removeDataWithUserDefaultsForKey:_versionCode];
            [WShareUtil saveDataWithUserDefaultsSetObject:returnDic ForKey:@"_versionCode"];

            [self update:_versionCode isRequired:isRequired];//后台(商店)版本号//解注

            //         [self update:@"2.0"];//注释

//            WLog(@"版本内容-> %@",_content);
//            WLog(@"下载地址-> %@",_appPath);
//            WLog(@"新版本号-> %@",_versionCode);
        }


    } failure:^(NSError *error) {
        WLog(@"失败");
    } showProgress:YES];
}

#pragma mark - 版本更新
-(void)update:(NSString *)banben isRequired:(NSString *)isRequired
{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    CFShow((__bridge CFTypeRef)(infoDictionary));
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];// app本地版本号

    /*
     WLog(@"%f",[banben doubleValue]);// 后台返回版本（商店版本）
     WLog(@"%f",[app_Version doubleValue]);// app本地版本号

     if ([banben doubleValue]>[app_Version doubleValue] && !isUpdate) {
     UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"版本更新" message:_content delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
     [av show];
     isUpdate = YES;
     }
     */
//    WLog(@"新后台返回版本（商店版本）%@",banben);// 后台返回版本（商店版本）
//    WLog(@"新app本地版本号%@",app_Version);// app本地版本号

    if ([banben compare:app_Version options:NSNumericSearch] == NSOrderedDescending) {

        if ([isRequired boolValue]) {
            UIAlertView *av1 = [[UIAlertView alloc] initWithTitle:@"版本更新" message:_content delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            av1.tag = 610;
            [av1 show];
        } else {
            UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"版本更新" message:_content delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            av.tag = 611;
            [av show];
        }
    }

}

// 对比版本号后，跳转商店更新版本
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{

    if (alertView.tag == 610){


        //        NSString  *urlStr = @"http://itunes.apple.com/app/id1153466604";//注释1250271269财税通--1153466604纪检委
        //        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];//注释
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_appPath]];//解注
    }else  if (alertView.tag == 611){
        if (buttonIndex == 1) {

            //        NSString  *urlStr = @"http://itunes.apple.com/app/id1153466604";//注释1250271269财税通--1153466604纪检委
            //        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];//注释
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_appPath]];//解注
        }
    }
}

-(void)dealloc{

    //停止监听网络状况.
    [_reachabilityManager stopMonitoring];

}

@end
